const express = require('express')
const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const app = express()
app.use(express.static(process.cwd()))

const port = process.argv[2] ? Number(process.argv[2].split('=')[1]) : 3000

app.use((req, res, next) => {
    console.log(req.path)
  // 返回当前目录下面的所有文件和文件夹数据
  if(fs.existsSync(process.cwd())) {
      let absPath = path.join(process.cwd(), decodeURIComponent(req.path))
      console.log(123, absPath)
      if(!absPath.includes('favicon.ico')) {
        let dirList = fs.readdirSync(absPath)
        dirList = dirList.map(item => {
            console.log(path.join(process.cwd(), item))
            return {
                title: item,
                path: item
            }
        })
        console.log(dirList)
        // 服务器端渲染页面=>前后端不分离
        let htmlView = fs.readFileSync(path.join(__dirname, 'views.html'), 'utf-8')
        let ejs = require('ejs');
        res.send(ejs.render(htmlView, {dirList}))
      } else {
          console.log('暂无图标')
      }
  }
  
})

app.listen(port, () => {
    childProcess.exec(`start http://localhost:${port}`)
    console.log(`服务已启动在http://localhost:${port}上`)
})